var saleProjectStore = null;
var salePremisesStore = null;
var saleBuildingStore = null;
var saleUnitStore = null;
var saleRoomStore = null;

Ext.define('component.marketing.salePanel', {
	extend : 'Ext.form.Panel',
	initComponent:function(){
		
		//项目
		saleProjectStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "projectName"],
	        proxy:{
	            type:'ajax',
	            url:contextPath+'/estate/project/findProjectList?resourcesCode=menu_0003_0001',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              }
	        } ,
	        autoLoad: false
		});
		saleProjectStore.load({
			callback:function(records, options, success){
				var count = saleProjectStore.getCount();
				if(count>0){
					var id = saleProjectStore.getAt(0).get("id");
					Ext.getCmp('saleProjectStore').setValue(id)
				}
				if(Ext.Array.contains(idata,"marketing:list:all")){
					var data = {"projectName": "全部", "id": '-1'};
					var rs = Ext.create(data);
					saleProjectStore.insert(count+1, rs);
				}
			}
		});
		//组团
		salePremisesStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "groupName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectPremises/findPremisesList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		
		salePremisesStore.on("beforeload", function(){
			salePremisesStore.removeAll();
			saleBuildingStore.removeAll();
			saleUnitStore.removeAll();
			saleRoomStore.removeAll();
			Ext.getCmp("salePremisesStore").setValue("");
			Ext.getCmp("saleBuildingStore").setValue("")
			Ext.getCmp("saleUnitStore").setValue("")
			Ext.getCmp("saleRoomStore").setValue("")
			var projectId = Ext.getCmp("saleProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			salePremisesStore.proxy.extraParams.projectId = projectId;
		});
		//楼栋
		saleBuildingStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "buildingName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectBuilding/findBuildingList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		saleBuildingStore.on("beforeload", function(){
			saleBuildingStore.removeAll();
			saleUnitStore.removeAll();
			saleRoomStore.removeAll();
			Ext.getCmp("saleBuildingStore").setValue("")
			Ext.getCmp("saleUnitStore").setValue("")
			Ext.getCmp("saleRoomStore").setValue("")
			var projectId = Ext.getCmp("saleProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("salePremisesStore").getValue();
			saleBuildingStore.proxy.extraParams.projectId = projectId;
			saleBuildingStore.proxy.extraParams.premisesId = premisesId;
		});
		//单元
		saleUnitStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "unitName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectUnit/findUnitList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		saleUnitStore.on("beforeload", function(){
			saleUnitStore.removeAll();
			saleRoomStore.removeAll();
			Ext.getCmp("saleUnitStore").setValue("")
			Ext.getCmp("saleRoomStore").setValue("")
			var projectId = Ext.getCmp("saleProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("salePremisesStore").getValue();
			var buildingId = Ext.getCmp("saleBuildingStore").getValue();
			saleUnitStore.proxy.extraParams.projectId = projectId;
			saleUnitStore.proxy.extraParams.premisesId = premisesId;
			saleUnitStore.proxy.extraParams.buildingId = buildingId;
		});
		//房间
		saleRoomStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "roomName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectRoom/findRoomList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		saleRoomStore.on("beforeload", function(){
			saleRoomStore.removeAll();
			Ext.getCmp("saleRoomStore").setValue("")
			var projectId = Ext.getCmp("saleProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("salePremisesStore").getValue();
			var buildingId = Ext.getCmp("saleBuildingStore").getValue();
			var unitId = Ext.getCmp("saleUnitStore").getValue();
			saleRoomStore.proxy.extraParams.projectId = projectId;
			saleRoomStore.proxy.extraParams.premisesId = premisesId;
			saleRoomStore.proxy.extraParams.buildingId = buildingId;
			saleRoomStore.proxy.extraParams.unitId = unitId;
		});
		
		var formsp = Ext.create("Ext.form.Panel", {
			minHeight:60,
		    title: "查询条件",
		    collapsible: true,  //可折叠
		    autoScroll: false,   //自动创建滚动条
		    defaultType: 'textfield',
		    defaults: {
		    	 anchor: '100%'
		    },
		    fieldDefaults: {
		        margin: 2,
		        labelWidth: 80,
		        labelAlign: "right",
		        margin: "5 0 5 0"
		    },
		    items: [{
			    xtype: "container",
			    layout: "hbox",
			    items: [
					{  
			            xtype:'combobox',
			            id:'saleProjectStore',
			            name: "projectId",
			            store: saleProjectStore,
			            valueField: "id",  
			            displayField: "projectName",
			            fieldLabel:'所属项目',
			            queryMode:'local',
			            typeAhead: true,
			            listeners:{
			            	'change':function(value){
			            		//加载组团数据
			            		if(value.lastValue && value.lastValue != "-1"){
			            			salePremisesStore.load({
			            				callback: function(records, operation, success){
			            					//若无组团数据，加载楼栋
			            					var recordLen = records.length;
			            					if(recordLen == 0){
			            						saleBuildingStore.load();
			            					}
			            				}
			            			});
			            		}else{
			            			salePremisesStore.removeAll();
			            			saleBuildingStore.removeAll();
			            			saleUnitStore.removeAll();
			            			saleRoomStore.removeAll();
			            			Ext.getCmp("salePremisesStore").setValue("");
			            			Ext.getCmp("saleBuildingStore").setValue("")
			            			Ext.getCmp("saleUnitStore").setValue("")
			            			Ext.getCmp("saleRoomStore").setValue("")
			            		}
			            	}
			            }
			        },
					{  
			            xtype:'combobox',
			            id:'salePremisesStore',
			            name: "premisesId",
			            store: salePremisesStore,
			            valueField: "id",  
			            displayField: "groupName",
			            queryMode:'local',
			            typeAhead: true,
			            listeners:{
			            	'change':function(value){
			            		//加载楼栋
			            		//若无楼栋数据，加载单元
			            		if(value.lastValue && value.lastValue != "-1"){
			            			saleBuildingStore.load({
			            				callback: function(records, operation, success){
			            					//若无组团数据，加载楼栋
			            					var recordLen = records.length;
			            					if(recordLen == 0){
			            						saleUnitStore.load();
			            					}
			            				}
			            			});
			            		}
			            	}
			            }
			        },
					{  
			            xtype:'combobox',
			            id:'saleBuildingStore',
			            name: "buildingId",
			            store: saleBuildingStore,
			            valueField: "id",  
			            displayField: "buildingName",
			            queryMode:'local',
			            typeAhead: true,
			            listeners:{
			            	'change':function(value){
			            		//加载单元
			            		//若无单元数据，加载房间
			            		if(value.lastValue && value.lastValue != "-1"){
			            			saleUnitStore.load({
			            				callback: function(records, operation, success){
			            					//若无组团数据，加载楼栋
			            					var recordLen = records.length;
			            					if(recordLen == 0){
			            						saleRoomStore.load();
			            					}
			            				}
			            			});
			            		}
			            	}
			            }
			        },
					{  
			            xtype:'combobox',
			            id:'saleUnitStore',
			            name: "unitId",
			            store: saleUnitStore,
			            valueField: "id",  
			            displayField: "unitName",
			            queryMode:'local',
			            typeAhead: true,
			            listeners:{
			            	'change':function(value){
			            		//加载房间
			            		if(value.lastValue && value.lastValue != "-1"){
			            			saleRoomStore.load();
			            		}
			            	}
			            }
			        },
					{  
			            xtype:'combobox',
			            id:'saleRoomStore',
			            name: "id",
			            store: saleRoomStore,
			            valueField: "id",  
			            displayField: "roomName",
			            queryMode:'local',
			            typeAhead: true
			        }
				]
			},{
	            xtype: "container",
	            layout: "hbox",
	            items: [
		            //权限资源隐藏字段
					{xtype:"textfield", name:"resourcesCode", value: resourcesCode, hidden: true},
					{xtype:"textfield", name:"resourcesName", value: "resName_pin_list", hidden: true},
                    { xtype: "textfield", name: "buildingArea", fieldLabel: "建筑面积" }
	            ]
			}],
		    buttons: [
				{ xtype: "button", text: "查询", 
	  	        	handler:function(){
	  	        		gridStoresp.load();
	  	        		var pagingTool=Ext.getCmp("pagingToolk");
	  	        		pagingTool.moveFirst();//跳至第一页
	  	        	}  
	  	        },
	  	        { xtype: "button", text: "清空",
	  	        	handler:function(){
	  	        		formsp.getForm().reset();
	  	        	}
	  	        }
	  	    ]
		});
	
		var gridStoresp = Ext.create('Ext.data.Store', {
        	fields: ["id", "combinedName"
                 , "houseTypeName","buildingArea","sharingArea"
                 ,"innerArea","billingArea","buildingPrice","totalAmount","day",
                 "danjia","zongjia","valuationType"],
        	pageSize: 10,  //页容量5条数据
        	//是否在服务端排序 （true的话，在客户端就不能排序）
        	remoteSort: false,
        	proxy: {
	            type: 'ajax',
	            url: jypath+'/estate/projectRoom/list',
	            actionMethods: { read: 'POST' },
	            reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
	                type: 'json', //返回数据类型为json格式
	                root: 'rows',  //数据
	                totalProperty: 'total' //数据总条数
	            }
        	},
        	autoLoad: true  //即时加载数据
    	});
	
		gridStoresp.on("beforeload",function(){
        	Ext.apply(gridStoresp.proxy.extraParams,formsp.getForm().getValues());
        	var projectId = Ext.getCmp("saleProjectStore").getValue();
            if(projectId == "-1"){
            	gridStoresp.proxy.extraParams.projectId = "";
            }
			var newResCode = resourcesCode;
			if(resourcesCode != "menu_0003_0001"){
				newResCode = resourcesCode + ",menu_0003_0001";
			}
            gridStoresp.proxy.extraParams.resourcesCode = newResCode;
    	});
	
		var gridsp = Ext.create('Ext.grid.Panel', {
			minHeight:600,
	        store: gridStoresp,
	        columnLines: true,
	        selModel: new Ext.selection.CheckboxModel({checkOnly:true}),
	        columns: [
	        {
	            text     : '房号',
	            dataIndex: 'combinedName',
	            width:350,
	            renderer: function(value,cellmeta,record,rowIndex,columnIndex,store) {
	            	 var rec = gridsp.getStore().getAt(rowIndex);
	               	 var roomId = rec.get('id');
	               	 if(roomId!=null){
	               		 return "<a style='text-decoration:none;' href='javascript:openWindow("+roomId+")'>"+value+"</a>";
	               	 }
	           	 return value;
	           }
        	},{
	            text     : '房态',
	            renderer: function() {
	                return '可售';
	            }
	        },{
	            text     : '户型',
	            dataIndex: 'houseTypeName',
	            renderer : function(val) {
	                if (val == 0) {
	                    return '正常';
	                } else if (val == 1) {
	                    return '已关闭';
	                }
	                return val;
	            }
	        },{
	            text     : '建筑面积(平方米)',
	            dataIndex: 'buildingArea'
	        },{
	            text     : '分摊面积(平方米)',
	            dataIndex: 'sharingArea'
	        },{
	            text     : '套内面积(平方米)',
	            dataIndex: 'innerArea'
	        },{
	            text     : '计价面积(平方米)',
	            dataIndex: 'valuationType',
	            renderer : function(value,cellmeta,record,rowIndex,columnIndex,store) {
	                var rec = gridsp.getStore().getAt(rowIndex);
	            	if(rec.get('valuationType')==1){
	            		var open = rec.get('buildingArea');
	                    return open;
	                } else if (rec.get('valuationType')==2) {
	                	var open = rec.get('innerArea');
	                    return open;
	                }
	                return value;
	            }
	        },{
	            text     : '单价(元)',
	            dataIndex: 'danjia', renderer: Ext.util.Format.numberRenderer('0,000.00')
	        },{  
	            text 	  : "总价(元)",  
	            dataIndex : 'zongjia', renderer: Ext.util.Format.numberRenderer('0,000.00')
	        },{  
	            text : "库存时间（天）",  
	            dataIndex : 'day'
	        }],
        	title: '可售列表',
	        dockedItems: [{
	            xtype: 'pagingtoolbar',  
	            store: gridStoresp,   // GridPanel中使用的数据  
	            dock: 'bottom',  
	            displayInfo: true,  
	            emptyMsg:"没有数据",  
	            displayMsg:"显示从{0}条数据到{1}条数据，共{2}条数据",
	            id:'pagingToolk'
	        }],
	        tbar: [
	   			{
		   			text:'批量销控',
		   			icon:jypath+'/resources/ExtJSicons/flag/flag_pink.png',
					handler:function(){
						var records = gridsp.getSelectionModel().getSelection();
	                	if(null==records || records == 0){
	                		Ext.Msg.alert('提示', '请选择房源！');
	                		return;
	                	}
	                	var roomIds = "";
	                	for(var ii=0; ii<records.length; ii++){
	                		if(roomIds){
	                			roomIds += ",";
	                		}
	                		roomIds += records[ii].data.id;
	                	}
	                	if(roomIds){
	                		var windowInfo=Ext.create('component.batch.sellControlWindow',{
								roomIds: roomIds,
							 	userName: userName
							});
							windowInfo.show();
	                	}
				    }
				}
			]
    	});
		
		var defaultConfiSP = {
			defaults: {  
		        split: true,    //有分割线  
		        collapsible: true  //可以折叠
		    },
			items:[formsp,gridsp]
		};
		
		Ext.apply(this,defaultConfiSP);
		this.callParent(arguments);
	}
});
